package com.luffer.springboot.demo.mqbasis.mqServer;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.PreparedStatement;

/**
 * @Author: dengkaibing
 * @Description:
 * @Date: 2021/8/3 14:25
 * @company 翼支付
 */
@Slf4j
public class BrokerServer implements Runnable{
    /**
     * 服务端口
     */
    public static int SERVICE_PORT=9999;

    private final Socket socket;

    public BrokerServer(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        //在try中设置写入流
        try (BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out=new PrintWriter(socket.getOutputStream())
        ){
            while (true) {
                String str=in.readLine();
                if(str == null){
                    continue;
                }
                log.info("接受到的原始数据：{}",str);
                if(str.equals("CONSUME")){
                    String message=Broker.consumeMessage();
                    out.println(message);
                    out.flush();
                }else {
                    Broker.produce(str);
                }
            }
        }
        catch (Exception e) {
            log.error("消息中心处理失败:",e);
        }
    }

    public static void main(String[] args) throws IOException {
        ServerSocket server=new ServerSocket(SERVICE_PORT);
        // 为每个消息中心处理请求起一个新线程处理
        while (true){
            log.info("消息处理中心启动:");
            BrokerServer brokerServer = new BrokerServer(server.accept());
            new Thread(brokerServer).start();
        }
    }
}
